import networkx as nx
import csv
import numpy as np

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = int(float(record[item]))
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

print '---------------------------------------------------------'
#filepath = 'C:/_DATA/migration_census_2000/STATE/'
#filepath = 'C:/_DATA/migration_census_2000/'
#filepath = 'C:/_DATA/migration_census_2009/'
filepath = 'C:/_DATA/migration_census_2000/REDCAPLUS_25Region/'
contiguityCSV = filepath + 'cnty_redcaplus_25regs.shp.ctg'
spContiguity = build_data_list(contiguityCSV)

id = np.unique(spContiguity[:,0])
ctgdic = {}

for item in id:
    ctgdic[item] = []

for item in spContiguity:
    if item[0] <> item[1]:
        ctgdic[item[0]].append(item[1])

#print ctgdic
G = nx.Graph(ctgdic)
length = nx.all_pairs_dijkstra_path_length(G)
lengthList = []
#for key in length.keys():
    #lengthList.append(length[key])

for i in range(len(id)):
    for j in range(len(id)):
        lengthList.append(length[i][j])
lengthList = np.array(lengthList)
lengthList.shape = (len(id), -1)
print lengthList
fileLoc = filepath + '25regs_graphdistance.csv'
np.savetxt(fileLoc, lengthList, delimiter=',', fmt = '%s')